package ua.com.musicdownloader.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import ua.com.musicdownloader.utils.Utils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Enumeration;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Ostap
 * Date: 16.05.12
 * Time: 23:40
 * To change this template use File | Settings | File Templates.
 */
public class UploadFileController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("info") != null) {
            String tmp = null;
            File dir = null;
            String[] params = {"genre", "band", "album"};
            for (String param : params) {
                tmp = request.getParameter(param);
                if (tmp.equals("") || tmp == null) {
//                    response.sendRedirect("uploadMusic.jsp");
//                    TODO validation
                }
                if (params.equals("genre")) {
                    dir = new File(tmp);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                } else {
                    dir = new File(dir, tmp);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                }
            }
            HttpSession session = request.getSession();
            synchronized (session) {
                session.setAttribute("directory", dir);
            }
            request.setAttribute("songs", Utils.getStringArrayDummy(Integer.parseInt(request.getParameter("number"))));
            request.getRequestDispatcher("WEB-INF/upload.jsp").forward(request, response);

        } else {
//            TODO Normal try caght block (IO)
            File dir = null;
            HttpSession session = request.getSession();
            synchronized (session) {
               dir = (File) session.getAttribute("directory");
            }

            try {
                List<FileItem> ls = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                for (FileItem fileItem : ls) {
                    if (!fileItem.isFormField()) {
                        InputStream inputStream = fileItem.getInputStream();
                        BufferedInputStream in = new BufferedInputStream(inputStream);
                        File file = new File(dir,fileItem.getName());
                        OutputStream outputStream = new FileOutputStream(file);
                        BufferedOutputStream out = new BufferedOutputStream(outputStream);
                        int read = 0;
                        while ((read = in.read()) != -1) {
                            out.write(read);
                        }
                        out.flush();
                        out.close();
                        in.close();

                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }
    }


}
